package com.wyh.common.exception;

import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;
import com.wyh.common.result.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.validation.BindException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.util.StringUtils;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.validation.BindException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;
import javax.validation.ConstraintViolationException;
import java.util.HashSet;
import java.util.Set;

/**
 * <p>
 * 全局异常捕捉
 * </p>
 *
 * @author 骸音
 * @since 2024-5-14
 */
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    // 处理 HttpMessageNotReadableException
//    @ExceptionHandler(HttpMessageNotReadableException.class)
//    @ResponseBody
//    public Result handleHttpMessageNotReadableException(HttpMessageNotReadableException ex) {
//        log.error("JSON parse error: ", ex);
//        return Result.error("402", "输入数字类型不合法");
//    }

    // 统一异常处理@ExceptionHandler, 主要用于Exception
    @ExceptionHandler(Exception.class)
    @ResponseBody//返回json串
    public Result error(HttpServletRequest request, Exception e){
        log.error("异常信息：",e);
        return Result.error(StringUtils.hasLength(e.getMessage())? e.getMessage() :"操作失败");
    }

    // 处理 MethodArgumentNotValidException (用于处理 @Valid 注解导致的验证错误)
    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseBody
    public Result handleMethodArgumentNotValidException(MethodArgumentNotValidException ex) {
        StringBuilder errorMessage = new StringBuilder();
        ex.getBindingResult().getAllErrors().forEach(error -> errorMessage.append(error.getDefaultMessage()).append("; "));
        return Result.error(errorMessage.toString());
    }

    // 处理 BindException (用于处理 @Valid 注解导致的验证错误)
    @ExceptionHandler(BindException.class)
    @ResponseBody
    public Result handleBindException(BindException ex) {
        StringBuilder errorMessage = new StringBuilder();
        ex.getBindingResult().getAllErrors().forEach(error -> errorMessage.append(error.getDefaultMessage()).append("; "));
        return Result.error(errorMessage.toString());
    }

    // 处理 ConstraintViolationException (用于处理方法参数上的验证错误)
    @ExceptionHandler(ConstraintViolationException.class)
    @ResponseBody
    public Result handleConstraintViolationException(ConstraintViolationException ex) {
        StringBuilder errorMessage = new StringBuilder();
        Set<String> errorMessages = new HashSet<>();
        ex.getConstraintViolations().forEach(cv -> {
            String message = cv.getMessage();
            errorMessages.add(message);
        });
        errorMessages.forEach(msg -> errorMessage.append(msg).append("; "));
        return Result.error(errorMessage.toString());
    }

    // 处理自定义异常 CustomException
    @ExceptionHandler(CustomException.class)
    @ResponseBody//返回json串
    public Result customError(HttpServletRequest request, CustomException e){
        return Result.error(e.getCode(), e.getMsg());
    }
    @ExceptionHandler(HttpMessageNotReadableException.class)
    @ResponseBody
    public Result messageError(HttpServletRequest request,HttpMessageNotReadableException e){
        return Result.error("400","参数非法");
    }
//    @ExceptionHandler(BindException.class)
//    @ResponseBody
//    public Result methodError(HttpServletRequest request,BindException e){
//        String failMsg = e.getBindingResult().getFieldError().getDefaultMessage();
//        return Result.error("400",failMsg);
//    }


}
